﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ComUIControl
{
    public class WaitBoxAsync
    {
        public static void Show(string text)
        {
            WaitBoxAsync.Instance.CreatForm(text);
        }

        public static void Close()
        {
            WaitBoxAsync.Instance.CloseForm();
        }

        private static WaitBoxAsync _instance;
        private static readonly Object syncLock = new Object();
        private static bool isActivated = false;

        public static WaitBoxAsync Instance
        {
            get
            {
                if (WaitBoxAsync._instance == null)
                {
                    lock (syncLock)
                    {
                        if (WaitBoxAsync._instance == null)
                        {
                            WaitBoxAsync._instance = new WaitBoxAsync();
                        }
                    }
                }
                return WaitBoxAsync._instance;
            }
        }

        private WaitBoxAsync()
        {
        }

        private FormWaitting waitForm;
        private SynchronizationContext context;

        public void CreatForm(string waitInfo)
        {
            if (isActivated || (waitForm != null && !waitForm.IsDisposed))
            {
                waitForm.SetTip(waitInfo);
                waitForm.ReLayout();
                return;
            }
            Task.Factory.StartNew(
              () =>
              {
                  waitForm = new FormWaitting();
                  context = SynchronizationContext.Current;
                  waitForm.SetTip(waitInfo);
                  isActivated = true;
                  waitForm.ShowDialog();
                  //Application.Run(waitForm);
                  isActivated = false;
              });
        }

        public void CloseForm()
        {
            if (isActivated || (waitForm != null && !waitForm.IsDisposed))
            {
                context.Post(delegate
                {
                    waitForm.Close();
                    waitForm.Dispose();
                    waitForm = null;
                }, null);             
            }
        }
    }
}
